{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "'''\n",
    "线性回归的简洁实现\n",
    "'''\n",
    "from mxnet import autograd, nd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "'''\n",
    "生成数据集\n",
    "'''\n",
    "num_inputs = 2\n",
    "num_examples = 1000\n",
    "true_w = [2, -3.4]\n",
    "true_b = 4.2\n",
    "features = nd.random.normal(scale=1, shape=(num_examples, num_inputs))\n",
    "labels = true_w[0] * features[:,0] + true_w[1] * features[:,1] + true_b\n",
    "labels += nd.random.normal(scale=0.01, shape=labels.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "'''\n",
    "读取数据集\n",
    "'''\n",
    "from mxnet.gluon import data as gdata\n",
    "batch_size = 10\n",
    "# 将训练数据的特征和标签组合\n",
    "dataset = gdata.ArrayDataset(features, labels)\n",
    "# 随机读取小批量\n",
    "data_iter = gdata.DataLoader(dataset, batch_size, shuffle=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "[[-0.9523637   0.92881453]\n",
      " [ 0.64431787  0.03414757]\n",
      " [ 1.934676   -0.28565592]\n",
      " [-0.52868146 -0.29051137]\n",
      " [-0.6904092   0.09003329]\n",
      " [ 0.12624073 -1.168922  ]\n",
      " [ 1.622939   -0.3708129 ]\n",
      " [ 1.1800286  -0.8387458 ]\n",
      " [-0.8693359   0.70957047]\n",
      " [ 0.42972964 -0.8840267 ]]\n",
      "<NDArray 10x2 @cpu(0)> \n",
      "[-0.87666404  5.3646502   9.036529    4.133816    2.5108895   8.4223585\n",
      "  8.708801    9.413779    0.05083627  8.061061  ]\n",
      "<NDArray 10 @cpu(0)>\n"
     ]
    }
   ],
   "source": [
    "for X, y in data_iter:\n",
    "    print(X, y)\n",
    "    break"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "'''\n",
    "定义模型\n",
    "'''\n",
    "from mxnet.gluon import nn\n",
    "net = nn.Sequential()\n",
    "# 在Gluon中，全连接层是⼀个Dense实例。我们定义该层输出个数为1\n",
    "net.add(nn.Dense(1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "'''\n",
    "初始化模型参数\n",
    "'''\n",
    "from mxnet import init\n",
    "\n",
    "net.initialize(init.Normal(sigma=0.01))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "'''\n",
    "定义损失函数\n",
    "'''\n",
    "from mxnet.gluon import loss as gloss\n",
    "\n",
    "loss = gloss.L2Loss() # 平方损失又称L2范数损失"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "'''\n",
    "定义优化算法\n",
    "通过collect_params函数获取模型中的参数\n",
    "'''\n",
    "from mxnet import gluon\n",
    "\n",
    "trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': 0.03})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, loss 0.034931\n",
      "epoch 2, loss 0.000124\n",
      "epoch 3, loss 0.000049\n"
     ]
    }
   ],
   "source": [
    "'''\n",
    "训练模型\n",
    "'''\n",
    "num_epochs = 3\n",
    "for epoch in range(1, num_epochs + 1):\n",
    "    for X, y in data_iter:\n",
    "        with autograd.record():\n",
    "            l = loss(net(X), y)\n",
    "        l.backward()\n",
    "        trainer.step(batch_size)\n",
    "    l = loss(net(features), labels)\n",
    "    print('epoch %d, loss %f' % (epoch, l.mean().asnumpy()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "([2, -3.4],\n",
       " \n",
       " [[ 1.99946   -3.3997319]]\n",
       " <NDArray 1x2 @cpu(0)>)"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dense = net[0]\n",
    "true_w, dense.weight.data()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(4.2,\n",
       " \n",
       " [4.1998196]\n",
       " <NDArray 1 @cpu(0)>)"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "true_b, dense.bias.data()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
